/**
 * 组长核对相关API接口
 */

const { post, get } = require('./request.js');

/**
 * 组长核对API接口集合
 */
const leaderApprovalApi = {
  /**
   * 获取待审核列表
   * @returns {Promise} API响应
   */
  getPendingList() {
    return post('/leaderCheck/noCheckList');
  },

  /**
   * 获取已审核列表 
   * @returns {Promise} API响应
   */
  getCheckedList() {
    return post('/leaderCheck/checkedList');
  },

  /**
   * 获取未通过列表（已拒绝列表）
   * @returns {Promise} API响应
   */
  getRejectedList() {
    return post('/leaderCheck/noPassList');
  },

  /**
   * 通过审核
   * @param {string} id 工资记录表id
   * @param {string} remark 备注
   * @returns {Promise} API响应
   */
  approve(id, remark = '') {
    return post(`/leaderCheck/agree?id=${encodeURIComponent(id)}&remark=${encodeURIComponent(remark)}`);
 
  },

  /**
   * 拒绝审核
   * @param {string} id 工资记录表id
   * @param {string} remark 备注
   * @returns {Promise} API响应
   */
  reject(id, remark = '') {
    return post(`/leaderCheck/reject?id=${encodeURIComponent(id)}&remark=${encodeURIComponent(remark)}`);
  },

  /**
   * 修改工序号、数量
   * @param {Object} params 修改参数
   * @param {string} params.id 记录ID
   * @param {string} params.productCode 产品代码
   * @param {string} params.processCode 工序代码
   * @param {string} params.quantity 数量
   * @returns {Promise} API响应
   */
  updateProcess(params) {
    const { id, productCode, processCode, quantity } = params;
    
    // 根据接口文档，使用POST请求体（JSON格式）
    const requestData = {
      id: String(id || ''),
      productCode: String(productCode || ''),
      processCode: String(processCode || ''),
      quantity: String(quantity || '')
    };
    
    return post('/leaderCheck/updateProcess', requestData);
  }
};

/**
 * 获取待审核数据并格式化
 * @returns {Promise<Object>} 格式化后的数据
 */
const fetchPendingApprovals = async () => {
  try {
    const response = await leaderApprovalApi.getPendingList();
    
    if (response.code === 200 && response.data) {
      const { total = 0, list = [] } = response.data;
      
      // 格式化数据为前端需要的结构
      const formattedList = list.map(user => ({
        username: user.username,
        account: user.account,
        products: user.productList?.map(product => ({
          productName: product.productName,
          productCode: product.productCode,
          processes: product.processList?.map(process => ({
            id: process.id || `${user.account}_${product.productCode}_${process.processCode}`,
            processName: process.processName,
            processCode: process.processCode,
            price: parseFloat(process.price || 0),
            quantity: parseInt(process.quantity || 0),
            totalPrice: parseFloat(process.totalPrice || 0),
            createTime: process.createTime,
            remark: process.remark || '待核对',
            status: 'pending'
          })) || []
        })) || []
      }));

      return {
        success: true,
        data: {
          total,
          list: formattedList
        },
        message: '获取待审核列表成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '获取待审核列表失败'
      };
    }
  } catch (error) {
    return {
      success: false,
      message: error.message || '网络请求失败'
    };
  }
};

/**
 * 获取已审核数据并格式化
 * @returns {Promise<Object>} 格式化后的数据
 */
const fetchCheckedApprovals = async () => {
  try {
    const response = await leaderApprovalApi.getCheckedList();
    
    if (response.code === 200 && response.data) {
      const { total = 0, list = [] } = response.data;
      
      // 格式化数据为前端需要的结构
      const formattedList = list.map(user => ({
        username: user.username,
        account: user.account,
        products: user.productList?.map(product => ({
          productName: product.productName,
          productCode: product.productCode,
          processes: product.processList?.map(process => ({
            id: process.id || `${user.account}_${product.productCode}_${process.processCode}`,
            processName: process.processName,
            processCode: process.processCode,
            price: parseFloat(process.price || 0),
            quantity: parseInt(process.quantity || 0),
            totalPrice: parseFloat(process.totalPrice || 0),
            createTime: process.createTime,
            remark: process.remark || '已完成',
            status: 'approved'
          })) || []
        })) || []
      }));

      return {
        success: true,
        data: {
          total,
          list: formattedList
        },
        message: '获取已审核列表成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '获取已审核列表失败'
      };
    }
  } catch (error) {
    return {
      success: false,
      message: error.message || '网络请求失败'
    };
  }
};

/**
 * 批准工序记录
 * @param {string} recordId 记录ID
 * @param {string} remark 备注
 * @returns {Promise<Object>} 操作结果
 */
const approveRecord = async (recordId, remark = '') => {
  try {
    const response = await leaderApprovalApi.approve(recordId, remark);
    
    if (response.code === 200 || response.code === 0) {
      return {
        success: true,
        message: response.message || '审核通过成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '审核通过失败'
      };
    }
  } catch (error) {
    return {
      success: false,
      message: error.message || '网络请求失败'
    };
  }
};

/**
 * 拒绝工序记录
 * @param {string} recordId 记录ID
 * @param {string} remark 拒绝原因
 * @returns {Promise<Object>} 操作结果
 */
const rejectRecord = async (recordId, remark = '') => {
  try {
    const response = await leaderApprovalApi.reject(recordId, remark);
    
    if (response.code === 200 || response.code === 0) {
      return {
        success: true,
        message: response.message || '审核拒绝成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '审核拒绝失败'
      };
    }
  } catch (error) {
    return {
      success: false,
      message: error.message || '网络请求失败'
    };
  }
};

/**
 * 修改工序信息
 * @param {Object} updateData 修改数据
 * @returns {Promise<Object>} 操作结果
 */
const updateProcessRecord = async (updateData) => {
  try {
    const response = await leaderApprovalApi.updateProcess(updateData);
    
    if (response.code === 200 || response.code === 0) {
      return {
        success: true,
        message: response.message || '修改成功'
      };
    } else {
      return {
        success: false,
        message: response.message || '修改失败'
      };
    }
  } catch (error) {
    return {
      success: false,
      message: error.message || '网络请求失败'
    };
  }
};

/**
 * 获取统计数据
 * @returns {Promise<Object>} 统计信息
 */
const getApprovalStatistics = async () => {
  try {
    // 并行获取待审核、已审核和已拒绝数据
    const [pendingResult, checkedResult, rejectedResult] = await Promise.all([
      fetchPendingApprovals(),
      fetchCheckedApprovals(),
      getRejectedRecords()
    ]);

    const pendingCount = pendingResult.success ? (pendingResult.data.total || 0) : 0;
    const checkedCount = checkedResult.success ? (checkedResult.data.total || 0) : 0;
    const rejectedCount = rejectedResult.success ? (rejectedResult.data.total || 0) : 0;

    // 计算今日审核数量（从已审核列表中筛选今日数据）
    let todayApproved = 0;
    if (checkedResult.success && checkedResult.data && checkedResult.data.list) {
      const today = new Date().toDateString();
      checkedResult.data.list.forEach(user => {
        user.products.forEach(product => {
          product.processes.forEach(process => {
            const processDate = new Date(process.createTime).toDateString();
            if (processDate === today) {
              todayApproved++;
            }
          });
        });
      });
    }

    const finalStatistics = {
      pendingCount,
      approvedCount: checkedCount,
      rejectedCount,
      todayApproved
    };

    return {
      success: true,
      data: finalStatistics
    };
  } catch (error) {
    return {
      success: false,
      data: {
        pendingCount: 0,
        approvedCount: 0,
        rejectedCount: 0,
        todayApproved: 0
      }
    };
  }
};

/**
 * 获取已拒绝记录并格式化
 * @returns {Promise<Object>} 格式化后的数据
 */
const getRejectedRecords = async () => {
  try {
    const response = await leaderApprovalApi.getRejectedList();
    
    if (response.code === 200 || response.code === 0) {
      const rawData = response.data || {};
      
      // 从响应数据中提取数组
      const { total = 0, list = [] } = rawData;
      
      // 格式化数据为前端需要的结构 - 参照待核对数据的格式化方式
      const formattedList = list.map(user => ({
        username: user.username,
        account: user.account,
        rejectTime: user.rejectTime || user.updateTime || user.createTime || '',
        products: user.productList?.map(product => ({
          productName: product.productName,
          productCode: product.productCode,
          processes: product.processList?.map(process => ({
            id: process.id || `${user.account}_${product.productCode}_${process.processCode}`,
            processName: process.processName,
            processCode: process.processCode,
            price: parseFloat(process.price || 0),
            quantity: parseInt(process.quantity || 0),
            totalPrice: parseFloat(process.totalPrice || 0),
            createTime: process.createTime,
            workHours: process.workHours || 0,
            remark: process.remark || user.remark || '无拒绝原因',
            rejectReason: process.remark || user.remark || '无拒绝原因',
            status: 'rejected'
          })) || []
        })) || []
      }));

      
      return {
        success: true,
        data: {
          total,
          list: formattedList
        },
        message: '获取已拒绝列表成功'
      };
    } else {
  
      return {
        success: false,
        data: {
          total: 0,
          list: []
        },
        message: response.message || '获取已拒绝列表失败'
      };
    }
  } catch (error) {

    return {
      success: false,
      data: {
        total: 0,
        list: []
      },
      message: error.message || '网络请求失败'
    };
  }
};

module.exports = {
  leaderApprovalApi,
  fetchPendingApprovals,
  fetchCheckedApprovals,
  getRejectedRecords,
  approveRecord,
  rejectRecord,
  updateProcessRecord,
  getApprovalStatistics
}; 